package com.ewing.web.action;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.ewing.busi.carry.model.WebCarryTemplate;
import com.ewing.busi.carry.model.WebCarryWay;
import com.ewing.busi.carry.service.CarryTemplateService;
import com.ewing.busi.carry.service.CarryWayService;
import com.ewing.busi.seller.service.SellerShopService;
import com.ewing.busi.system.model.SysParam;
import com.ewing.busi.system.service.SysParamService;
import com.ewing.common.constant.SysParamCode;
import com.ewing.common.exception.BusiException;
import com.ewing.common.exception.ShopException;
import com.ewing.common.exception.SysParamException;
import com.ewing.core.app.action.base.BaseAction;
import com.ewing.core.app.action.base.ResponseData;
import com.ewing.core.app.action.base.ResponseUtils;
import com.ewing.core.jdbc.util.PageBean;
import com.google.gson.reflect.TypeToken;

/**
 * 运费模板类
 * 
 * @author tanson lam
 * @creation 2015年1月10日
 */
public class CarryAction extends BaseAction {

	private static Logger logger = Logger.getLogger(MainAction.class);
	private static final String LIST_PAGE = "/admin/carry/carrylist.html";
	private static final String EDIT_FORM = "/admin/carry/carryform.html";

	@Resource
	private CarryTemplateService carryTemplateService;
	@Resource
	private SellerShopService sellerShopService;
	@Resource
	private SysParamService sysParamService;
	@Resource
	private CarryWayService carryWayService;

	/**
	 * 查詢列表
	 */
	public void show() {
		try {
			Map<String, Object> dataModel = new HashMap<String, Object>();
			String pageStr = request.getParameter("page");
			String pageSizeStr = request.getParameter("pageSize");
			Integer page = StringUtils.isEmpty(pageStr) ? null : Integer
					.valueOf(pageStr);
			Integer pageSize = StringUtils.isEmpty(pageSizeStr) ? null
					: Integer.valueOf(pageSizeStr);
			String condition = "shopId="
					+ sellerShopService.checkAndReturnShopId(getLoginUserId());
			PageBean<WebCarryTemplate> pageBean = baseModelService.pageQuery(
					condition, bulidOrderBySql(), pageSize, page,
					WebCarryTemplate.class);
			for (WebCarryTemplate webCarryTemplate : pageBean.getResult()) {
				translateWebCarryTemplate(webCarryTemplate);
			}
			List<SysParam> iseffCode = sysParamService
					.getSysParamByRoot(SysParamCode.ISEFF);
			dataModel.put("iseffCode", iseffCode);
			pageBean.setPageUrl(getPaginationUrl("/Admin-Carry-show.action"));
			dataModel.put("pageBean", pageBean);
			render(LIST_PAGE, dataModel);
		} catch (ShopException e) {
			renderAdminFail(e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	private void translateWebCarryTemplate(WebCarryTemplate webCarryTemplate)
			throws SysParamException {
		String carryWays = webCarryTemplate.getCarryWays();
		if (!StringUtils.isEmpty(carryWays)) {
			StringBuffer sb = new StringBuffer();
			String[] carrayWayArr = StringUtils.split(carryWays, ",");
			for (int i = 0; i < carrayWayArr.length; i++) {
				sb.append(sysParamService.getByValue(SysParamCode.CARRY_WAY,
						carrayWayArr[i]).getParamName());
				if (i < carrayWayArr.length - 1) {
					sb.append(",");
				}
			}
			webCarryTemplate.setCarryWays(sb.toString());
		}
	}

	/**
	 * 显示编辑表单
	 */
	public void showEditForm() {
		Map<String, Object> dataModel = new HashMap<String, Object>();
		try {
			String id = request.getParameter("id");
			Integer shopId = sellerShopService
					.checkAndReturnShopId(getLoginUserId());
			if (!StringUtils.isEmpty(id)) {
				WebCarryTemplate webCarryTemplate = carryTemplateService
						.findTemplate(Integer.valueOf(id), shopId);
				dataModel.put("bean", webCarryTemplate);
				List<String> checkCarryWayList = Arrays.asList(StringUtils
						.split(webCarryTemplate.getCarryWays(), ","));
				List<WebCarryWay> carryWayDataList = carryWayService
						.findByTemplateId(webCarryTemplate.getId());
				dataModel.put("checkCarryWayList", checkCarryWayList);
				dataModel.put("carryWayDataList", carryWayDataList);
			}
			List<SysParam> iseffCode = sysParamService
					.getSysParamByRoot(SysParamCode.ISEFF);
			dataModel.put("iseffCode", iseffCode);
			dataModel.put("carryWay",
					sysParamService.getSysParamByRoot(SysParamCode.CARRY_WAY));
			render(EDIT_FORM, dataModel);
		} catch (ShopException e) {
			renderAdminFail(e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 保存导航栏
	 */
	public void save() {
		ResponseData responseData = null;
		try {
			List<WebCarryWay> webCarryWayList = gson.fromJson(
					(String) request.getParameter("webCarryWayList"),
					new TypeToken<List<WebCarryWay>>() {
					}.getType());
			WebCarryTemplate webCarryTemplate = gson.fromJson(
					(String) request.getParameter("webCarryTemplate"),
					new TypeToken<WebCarryTemplate>() {
					}.getType());
			if (webCarryTemplate == null || webCarryWayList == null
					|| webCarryWayList.isEmpty()) {
				throw new BusiException("请完善运费模板内容");
			}
			webCarryTemplate.setShopId(sellerShopService
					.checkAndReturnShopId(getLoginUserId()));
			webCarryTemplate = carryTemplateService.saveOrUpdateTemplate(
					webCarryTemplate, webCarryWayList);
			responseData = ResponseUtils.success("保存成功！");
			responseData.setResult(webCarryTemplate.getId());
		} catch (BusiException e) {
			responseData = ResponseUtils.fail("保存失败！" + e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			responseData = ResponseUtils.fail("保存失败！", e.getMessage());
		}
		this.outResult(responseData);
	}

	/**
	 * 删除模板
	 */
	public void delete() {
		ResponseData responseData = null;
		try {
			String selectItems = request.getParameter("selectItems");
			Integer shopId = sellerShopService
					.checkAndReturnShopId(getLoginUserId());
			if (selectItems.isEmpty()) {
				responseData = ResponseUtils.fail("没有选中的数据！");
				this.outResult(responseData);
				return;
			}
			String[] selectArr = selectItems.split(",");
			for (String id : selectArr) {
				carryTemplateService
						.deleteTemplate(Integer.valueOf(id), shopId);
			}
			responseData = ResponseUtils.success("删除成功！");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			responseData = ResponseUtils.fail("删除失败！");
		}
		this.outResult(responseData);
	}
}
